<template>
    <div class="divBox">
      <el-card class="box-card boxCard" shadow="hover" :body-style="{ paddingBottom: 0, borderBottom: 0 }">
        <el-form ref="formValidate" v-loading="fullscreenLoading" :rules="ruleValidate" :model="formValidate" size="small" class="formValidate mt20" label-width="120px" @submit.native.prevent>
          <!--添加活动【start】-->
          <el-row :gutter="24">
            <el-col v-bind="grid2">
              <el-form-item label="公司名称：" prop="name">
                <el-input v-model="formValidate.name" :disabled="isDisabled" maxlength="249" placeholder="请输入公司名称" />
              </el-form-item>
            </el-col>
            <el-col v-bind="grid2">
              <el-form-item label="手机号：" prop="mobile">
                <el-input v-model="formValidate.mobile" :disabled="isDisabled" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
          <el-col :span="24">
              <el-form-item label="公司LOGO：" prop="image">
              <div class="upLoadPicBox cover-box" :disabled="isDisabled">
                <div @click="modalPicTap('1')" v-if="formValidate.image" class="coverImg"><img v-lazy="$uploadURL(formValidate.image)"></div>
                <div @click="modalPicTap('1')" v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="公司轮播图：" prop="sliderImages">
              <div class="acea-row">
                <div
                  v-for="(item,index) in formValidate.sliderImages"
                  :key="index"
                  class="pictrue"
                  draggable="true"
                  @dragstart="handleDragStart($event, item)"
                  @dragover.prevent="handleDragOver($event, item)"
                  @dragenter="handleDragEnter($event, item, 'slider')"
                  @dragend="handleDragEnd($event, item)"
                >
                  <img v-lazy="$uploadURL(item)">
                  <i  class="el-icon-error btndel" @click="handleRemove(index)" />
                </div>
                <div v-if="formValidate.sliderImages.length < 10" class="upLoadPicBox" @click="modalPicTap('2')">
                  <div class="upLoad">
                    <i class="el-icon-camera cameraIconfont" />
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        <el-col :span="24">
            <el-form-item label="视频上传" prop="videos">
              <UploadVideo :guId="selectedId" :type="6" v-model="formValidate.videos" @change="videosChange" :newVideo="formValidate.videos"></UploadVideo>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-col :xs="20" :sm="24" :md="24" :lg="16" :xl="16">
              <el-form-item label="公司简介：" prop="content" class="detail">
                <ueditor-from v-model="formValidate.content" :content="formValidate.content" @input="editorInput"></ueditor-from>
              </el-form-item>
            </el-col>
            <el-col :xs="4" :sm="24" :md="24" :lg="8" :xl="8">
              <div class="iframe hidden-md-and-down">
                <div class="title">简介预览</div>
                <div class="content" v-html="formValidate.content"></div>
              </div>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否显示：" props="isShow" class="specType">
              <el-radio-group v-model="formValidate.isShow">
                <el-radio :label="1" class="radio">显示</el-radio>
                <el-radio :label="0">不显示</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="!routeId">
            <el-form-item label="是否绑定主账号：" props="userId" class="specType">
              <el-radio-group v-model="formValidate.userId">
                <el-radio :label="1" class="radio">绑定</el-radio>
                <el-radio :label="0">不绑定</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          </el-row>
          <!--添加活动【end】-->
          <el-form-item>
            <el-button type="primary" class="submission subCurLeft" @click="handleSubmit">提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
<script>
import { putCompanyApi,postCompanyApi,getCompanyIdApi } from "@/api/company";
import { mapGetters } from "vuex";
import UploadVideo from "@/components/uploadVideo/index.vue";
import ueditorFrom from '@/components/ueditorFrom';
import draggable from 'vuedraggable';
export default {
  name: "company",
  components: {
    UploadVideo,
    ueditorFrom,
    draggable
  },
  data() {
    return {
      imgSize: "60px",
      timeValue: [],
      routeId: "",
      // 双行
      grid2: {
        xl: 10,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24,
      },
      // 单行
      grid: {
        xl: 8,
        lg: 8,
        md: 8,
        sm: 12,
        xs: 24,
      },
      fileList: [],
      isDisabled: false,
      // 全屏加载
      fullscreenLoading: false,
      // 表单
      formValidate: {
        name:"",
        mobile:"",
        videos:"",
        content:"",
        image:"",
        sliderImage: '',
        sliderImages:[],
        isShow: 1,
        userId:null,
      },
      // 表单验证
      ruleValidate: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            required: true,
            min: 0,
            max: 100,
            message: "活动名称最多为50个字符",
            trigger: "blur",
          },
        ],
        mobile:[
               { required: true, message: '请输入手机号码', trigger: 'blur' },
               { validator:function(rule,value,callback){
                            if(/^1[34578]\d{9}$/.test(value) == false){
                                   callback(new Error("请输入正确的手机号"));
                            }else{
                                   callback();
                            }
                          }, trigger: 'blur'
                },
        ],
        content: [
          { required: true, message: "请输入活动详情", trigger: "blur" },
          {
            required: true,
            min: 0,
            max: 2000,
            message: "活动详情最多为1000个字符",
            trigger: "blur",
          },
        ],
        videos: [
          { required: true, message: '请上传公司视频',trigger: 'change' }
        ],
        image: [
          { required: true, message: '请上传商品图', trigger: 'change' }
        ],
        sliderImages: [
          { required: true, message: '请选择商品轮播图', type: 'array', trigger: 'change' }
        ],
        IsShow: [
          {
            required: true,
            message: "请选择是否展示活动",
            trigger: "blur",
          },
        ]
      },
    };
  },
  computed: {
    ...mapGetters(["customRouter","selectedId"]),
  },
  mounted() {
    this.routeId = this.$route.query.id;
    if (this.routeId) {
      getCompanyIdApi(this.selectedId,this.routeId)
        .then((res) => {
          this.formValidate.name = res.name,
          this.formValidate.mobile = res.mobile,
          this.formValidate.content = res.content,
          this.formValidate.image = res.image,
          this.formValidate.videos = res.videos,
          // this.formValidate.sliderImage = res.sliderImage,
          this.formValidate.isShow = res.isShow
          if(res.sliderImage != ""){
            this.formValidate.sliderImages=res.sliderImage.split(',')
          }else{
            this.formValidate.sliderImages = []
          }
          
          console.log("提交res", this.formValidate);
          this.$message.success("信息获取成功!");
        })
        .catch(() => {});
    }
    console.log("this.routeId>>>>>>>",this.routeId);
  },
  methods: {
    editorInput(e) {
      this.$refs[`formValidate`].validateField('content');
    },
    modalPicTap(tit, i) {
      const _this = this
        this.$modalUpload((data) => {
          console.log("imag>>>>>>>>",data);
          if (tit === '1') {
            _this.formValidate.image = data[0].path
            console.log("_this.formValidate.image",_this.formValidate.image);
            this.$refs['formValidate'].validateField('image');
          } else if (tit === '2') {
            if (data.length > 10) this.$message.warning('最多选择10张图片！')
            if ((data.length + _this.formValidate.sliderImages.length) > 10) this.$message.warning('最多选择10张图片！')
            const list = []
            data.forEach((item, index) => {
              if (_this.formValidate.sliderImages.length + index + 1 <= 10) list.push(item.path)
            })
            _this.formValidate.sliderImages.push(...list);
            if (this.formValidate.sliderImages.length > 0) this.$refs['formValidate'].validateField('sliderImages');
            this.$refs['formValidate'].validateField('sliderImages')
            console.log("_this.formValidate.sliderImage",_this.formValidate.sliderImages);
          }
        }, tit, '', '上传图片')
      
    },
    //删除图片
    handleRemove(index) {
      this.formValidate.sliderImages.splice(index, 1)
    },
    // 优先级移动
    handleDragStart(e, item) {
      if (!this.isDashboard) this.dragging = item
    },
    // 拖拽
    handleDragOver(e) {
      if (!this.isDisabled) e.dataTransfer.dropEffect = 'more'
    },
    // 手柄拖动拖拽图片
    handleDragEnter(e, item, drag) {
      if (!this.isDashboard) {
        if (drag === 'slider') {
          e.dataTransfer.effectAllowed = 'move'
          if (item === this.dragging) {
            return
          }
          const newItems = [...this.formValidate.sliderImages]
          const src = newItems.indexOf(this.dragging)
          const dst = newItems.indexOf(item)
          newItems.splice(dst, 0, ...newItems.splice(src, 1))
          this.formValidate.sliderImages = newItems
        } else {
          e.dataTransfer.effectAllowed = 'move'
          if (item === this.dragging) {
            return
          }
          const newItems = [...this.formValidate.activity]
          const src = newItems.indexOf(this.dragging)
          const dst = newItems.indexOf(item)
          newItems.splice(dst, 0, ...newItems.splice(src, 1))
          this.formValidate.activity = newItems
        }
      }
    },
    handleDragEnd($event, item) {
      if (!this.isDashboard) this.dragging = null
    },
    //视频
    videosChange(data) {
      this.formValidate.videos = data;
      console.log("视频===:", this.formValidate.videos);
    },
    //提交
    handleSubmit() {
      // const data = JSON.stringify(this.formValidate);
      const data = {
        name:this.formValidate.name, //公司名称，必填
        mobile: this.formValidate.mobile,//手机号
        image: this.formValidate.image,//公司logo，必填
        sliderImage: JSON.parse(JSON.stringify(this.formValidate.sliderImages)).join(','),//轮播图，支持上传多个(用逗号隔开)
        videos:this.formValidate.videos,//视频，支持上传多个(用逗号隔开)
        content: this.formValidate.content,//富文本,必填
        isShow: this.formValidate.isShow,
      }
      console.log("data>>>", data);
      this.fullscreenLoading = true;
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          if(this.routeId != null){
            // 更新活动
            putCompanyApi(this.selectedId,this.routeId,data)
            .then((res) => {
              console.log("提交res", res);
              this.$message.success("更新成功!");
              this.fullscreenLoading = false;
              setTimeout(() => {
                this.$router.push({
                  path: `${this.customRouter}/company/company_list`,
                });
              }, 500);
            })
            .catch(() => {
              this.fullscreenLoading = false;
            });
          }else{
            data.userId = this.formValidate.userId
            // 添加活动
            postCompanyApi(this.selectedId,data)
            .then((res) => {
              console.log("提交res", res);
              this.$message.success("新增成功!");
              this.fullscreenLoading = false;
              setTimeout(() => {
                this.$router.push({
                  path: `${this.customRouter}/company/company_list`,
                });
              }, 500);
            })
            .catch(() => {
              this.fullscreenLoading = false;
            });
          }
        } else {
          this.$message.error("请完善表单相关信息！");
          this.fullscreenLoading = false;
          return false;
        }
      });
    },
  },
};
</script>
  
<style lang="scss" scope>
.iframe {
  width: 344px;
  height: 644px;
  margin: 0 auto;
  border: 1px solid #eeeeee;
  border-radius: 40px;
  .title {
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-size: 14px;
    text-align: center;
  }
  .content {
    height: 560px;
    overflow: hidden;
    overflow-x: hidden;
    padding: 0 20px;
    overflow-y: auto;
    img {
      max-width: 100%;
    }
  }
}
.choiceFormat {
  .el-select {
    .el-input {
      .el-input__inner {
        border-radius: 4px 0 0 4px !important;
      }
    }
  }
  .el-button[type="button"] {
    border-radius: 0 3px 3px 0 !important;
  }
}
.upLoadPicBox {
  .coverImg {
    width: 58px;
    height: 58px;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
  }
  &.cover-box {
    cursor: auto;
  }
}

.subCurLeft {
  margin-left: 0 !important;
}

.disLabelmoren {
  .el-form-item__label {
    width: auto !important;
    margin-left: 120px !important;
  }
}

.selWidth {
  width: 100%;
}
.selWidthd {
  width: 300px;
}
.specType {
  .el-form-item__content {
    line-height: 40px;
  }
}

.color-item {
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #ffffff;
  margin-right: 10px;
}
.color-list {
  .color-item.blue {
    background-color: #1e9fff;
  }
  .color-item.yellow {
    background-color: rgb(254, 185, 0);
  }
  .color-item.green {
    background-color: #009688;
  }
  .color-item.red {
    background-color: #ed4014;
  }
}

.detail {
  .el-form-item__content {
    line-height: normal;
  }
}
.el-table {
  .cell {
    padding: 0 10px;
    .box {
      padding: 0 10px;
    }
  }
}

.tabNumWidth {
  ::v-deep .el-input-number--medium {
    width: 121px !important;
  }
  ::v-deep .el-input-number__increase {
    width: 20px !important;
    font-size: 12px !important;
  }
  ::v-deep .el-input-number__decrease {
    width: 20px !important;
    font-size: 12px !important;
  }
  ::v-deep .el-input-number--medium .el-input__inner {
    padding-left: 25px !important;
    padding-right: 25px !important;
  }
  ::v-deep thead {
    line-height: normal !important;
  }
  ::v-deep .el-table .cell {
    line-height: normal !important;
  }
}

.acea-row {
  .pictrue {
    width: 60px;
    height: 60px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    margin-right: 10px;
    position: relative;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
    .btndel {
      position: absolute;
      z-index: 1;
      left: 43px;
      top: -8px;
      font-size: 20px;
    }
  }
  .el-icon-circle-close {
    cursor: pointer;
  }
}

// 规格添加input框
.input-new-tag {
  width: 90px;
  margin-right: 10px;
  vertical-align: middle;
}

// 规格Tag样式
.type-tag {
  display: flex;
  align-items: center;
  .scopeType-tag-svg {
    cursor: move;
    svg {
      fill: red;
      font-size: 30px;
    }
  }
  .scopeType-tag {
    .rulesBox {
      display: flex;
      flex-wrap: wrap;
      align-items: self-start;
      .el-tag--light {
        cursor: move;
        padding-left: 30px;
        position: relative;
        &.el-tag--light::after {
          content: " ";
          display: block;
          width: 9px;
          height: 9px;
          border-radius: 50%;
          background-color: #2d8cf0;
          position: absolute;
          top: 8px;
          left: 10px;
        }
        .el-icon-close::before {
          margin-top: 1px;
          margin-right: 1px;
        }
      }
    }
    &.borderStyle {
      width: 90%;
      border: 1px solid #ccc;
      padding: 8px;
      border-radius: 4px;
    }
  }
}

// 处理input type = number的上下箭头
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type="number"] {
  -moz-appearance: textfield;
}

.boxCard {
  .el-card__header {
    padding-bottom: 0 !important;
    border-bottom: 0 !important;
  }
}
</style>
  